var param ;
// global var for modify.
var fireWallObj = {};
fireWallObj.backUpEditFireWallIDList = null;

$(function() {
	// initiate condition first.
	var ERROR_MSG_NULL = "不能为空";
	// fireWall array.
	var fireWallArray = [];
	// VDI IP arr.
	var vdi_insert_arr = [];
	// modify temp obj.
	var modify_obj_temp;
	
	FireWallModel.prototype.equals = function(that) {
		if(!that) {
			return false;
		}
		
		if(that.id || this.id) {
			return that.id == this.id;
		}
		else {
			if(this.vdiIp == that.vdiIp && this.targetIp == that.targetIp &&
					this.direction == that.direction && this.startTime == that.startTime &&
					this.endTime == that.endTime && this.port == that.port &&
					this.protocol == that.protocol && this.remark == that.remark) 
			{
				return true;
			}
			
			return false;
		}
	};
	
	// init equals function.
	VDIIPBean.prototype.equals= function(that) {
		if(!that) {
			return false;
		}
		
		if(that === this) {
			return true;
		}
		
		if(this.id == that.id) 
		{
			return true;
		}
		
		return false;
	};
	
	VDIIPBean.prototype.toString = function() {
		return this.ip + "";
	};
	
	VDIIPBean.prototype.toIDString = function() {
		return this.id + "";
	};
	
	// initiation the tree condition.
	if(fireWallObj.op == "editOne") {
		// modify situation.
		$.ajax({
			url: "getFireWallDetail.do?id=" + fireWallObj.fireWallID,
			type: 'POST',
			dataType:"json",
			success : function(data) {
				// init the edit one condition.
				$("#vdiIP").css("background-color", "lightGrey");
				$("#vdiIP").attr("disabled", true);
				$(".VDIAddTable").css("display", "none");
				$(".action_VDIInfoSubmit").css("display", "none");
				
				$(".addFireWallAction").css("display", "none");
				$(".addFireWallAction_editOne").css("display", "inline-block");
				//$(".action_VDICancel").css("float", "right").css("margin-right", "18%");
				$(".copyTitle").css("margin-left", "0px");
				$(".addFireWallAction").text("修改");
				$("#form_data").css("min-height", "480px");
				
				fillFireWallBaseData(data);
				
				fireWallObj.editOne = data;
			},
			error : function(e) {
				console.error("error", e);
			}
		});
	}
//	else if(fireWallObj.op == "edit") {
//	}
	// normal insert action.
	else {
		if(fireWallObj.op == "edit") {
			// 如果是tab页面的请求.
			$.ajax({
				url : "initFirewallList.do?vdiId=" + fireWallObj.vdiId,
				type : "post",
				dataType : "json"
			}).done(function(data) {
				if(data.vdiInfo) {
					$("#vdiIP").val(data.vdiInfo.ip);
					$("#vdiIP").attr("vdiIP", data.vdiInfo.ip);
					$("#vdiIP").attr("vdiID", data.vdiInfo.id);
				}
				
				if(data.result) {
					// init the edit condition.
					$("#vdiIP").css("background-color", "lightGrey");
					$("#vdiIP").attr("disabled", true);
					
					$(".action_VDICancel").css("display", "none");
					$(".action_VDIInfoSubmit").text("提交");
//					$(".action_VDIInfoSubmit").css('float','right').css('margin-right','18%');
					
					fireWallObj.backUpEditFireWallIDList = [];
					for(fireWallTab in data.result) {
						fireWallArray.push(new FireWallModel(
								data.result[fireWallTab].vdiIP, data.result[fireWallTab].targetIp,
								data.result[fireWallTab].direction,data.result[fireWallTab].startTime,
								data.result[fireWallTab].endTime,data.result[fireWallTab].port,
								data.result[fireWallTab].protocol,data.result[fireWallTab].remark,
								data.result[fireWallTab].id));
						
					    fireWallObj.backUpEditFireWallIDList.push(data.result[fireWallTab].id);
					}
					
					redrawFireWallGrid();
				}
				else{
					console.error("error occured when get fireWall by vdiID");
				}
			});
		}
		
		$.ajax({
			url: "getTreeData.do",
			type: 'POST',
			dataType:"json",
			async : false,
			success: function(data) {
				// initiate the tree data
				var data_temp = [];
				
				var data_htm = "[";
				// process the department.
				for(var tree_temp in data.dept) {
					data_htm += '{id:"' + convertSpecialChar(data.dept[tree_temp].deptId) + '",';
					data_htm += 'pId:"' + convertSpecialChar(data.dept[tree_temp].parentId) + '",';
					data_htm += 'name:"' + convertSpecialChar(data.dept[tree_temp].deptName) + '",';
					data_htm += 'open:"true",';
					data_htm += 'isParent:"true",';
					data_htm += 'titleTip:"' + convertSpecialChar(data.dept[tree_temp].deptName) + '"},';
				}
				
				for(var tree_temp in data.vdiIP) {
					data_htm += '{id:"' + convertSpecialChar(data.vdiIP[tree_temp].id) + '",';
					data_htm += 'pId:"' + convertSpecialChar(data.vdiIP[tree_temp].department) + '",';
					data_htm += 'iconSkin:"iconComputer",';
					data_htm += 'name:" VDI-'+ convertSpecialChar(data.vdiIP[tree_temp].ip) + '-' +
					convertSpecialChar(data.vdiIP[tree_temp].loginName) + '",';
					data_htm += 'isParent:"false",';
					data_htm += 'titleTip:" VDI-' + convertSpecialChar(data.vdiIP[tree_temp].ip) + '-' +
					convertSpecialChar(data.vdiIP[tree_temp].loginName) + '"},';
				}
				
				data_htm += "]";
				
				$.fn.zTree.init($("#vdiIPTree_ul"), {
					data : {key: {title:"titleTip"},
						simpleData: {enable: true}
					},
					check : {enable : true},
					callback : {
						onClick: function(event, treeId, treeNode) {
							// whether here need to be checked when click it.
							console.debug("tree click........", treeNode);
						},
						onCheck : function(event, treeId, treeNode) {
							(function() {
								if(arguments[0].isParent) {
									for(var fw_temp in arguments[0].children) {
										arguments.callee(arguments[0].children[fw_temp]);
									}
								}
								else {
									if(arguments[0].checked) {
										vdi_insert_arr.push(new VDIIPBean(arguments[0].id, arguments[0].name));
									}
									else {
										var vdi_del_temp = new VDIIPBean(arguments[0].id, arguments[0].name);
										
										for(var i = 0; i < vdi_insert_arr.length; i++) {
											if(vdi_del_temp.equals(vdi_insert_arr[i])) {
												vdi_insert_arr.splice(i);
												
												break;
											}
										}
									}
								}
							})(treeNode);
							
							// set the result in input.
							$("#vdiIP").val(vdi_insert_arr.toString());
						}
					}
				}, eval(data_htm));
				
				// private tree node bean.
				function TreeNodeBean(id, pid, name, isLeaf) {
					this.id = id;
					this.pid = pid;
					this.name = name;
					this.isLeaf = isLeaf;
				}
			},
			error : function() {
				console.error("error occured when get tree data.");
			}
		});
	}
	
	// bind action.
	$("#vdiIP").off("click").on("click", function(ev) {
		$(".vdiIPTree_div").slideDown("fast");
		// hide the tree.
		$("body").off("mousedown").on("mousedown", function(e) {
			if(!(e.target.id == "vdiIPTree_ul" || e.target.id == "vdiIP" ||
					$(e.target).parents(".vdiIPTree_div").length > 0 || 
					e.target.className == "vdiIPTree_div menuContent")) 
			{
				$(".vdiIPTree_div").slideUp("fast");
				
				// vdi ip can not be null.
				checkIPPrinceple(ev.target, /^.*$/, false, "");
				$("body").off("mousedown");
			}
		});
	});
	
	// target IP validation.
	$("#tIP").off("blur").on("blur", function(e) {
		checkIPPrinceple(e.target, /^(\d{1,3}\.){3}\d{1,3}$/, false, "IP不符合规则");
		
	}).off("keyup").on("keyup", function(e) {
		checkIPPrinceple(e.target, /^(\d{1,3}\.){3}\d{1,3}$/, false, "IP不符合规则");
	});
	
	// port validation.
	$("#tPort").off("blur").on("blur", function(e) {
		checkIPPrinceple(e.target, /^\d{1,5}$/, true, "端口需小于5位数字");
	}).off("keyup").on("keyup", function(e) {
		checkIPPrinceple(e.target, /^\d{1,5}$/, true, "端口需小于5位数字");
	});
	
	// protocol validation.
	$("#Proto").off("blur").on("blur", function(e) {
		checkIPPrinceple(e.target, /^\w*$/, true, "类型不能有特殊字符");
	}).off("keyup").on("keyup", function(e) {
		checkIPPrinceple(e.target, /^\w*$/, true, "类型不能有特殊字符");
	});
	
	// initiation the datepicker.
	$('#sDate').datepicker({
		dateFormat:'yy-mm-dd',
		onClose : function() {
			checkIPPrinceple($("#sDate"), null, false, "");
		}
	});
	
	$('#eDate').datepicker({
		dateFormat:'yy-mm-dd',
		onClose : function() {
			checkIPPrinceple($("#eDate"), null, false, "");
		}
	});
	
	// bind the add firewall action.
	$(".addFireWallAction").off("click").on("click", function() {
		// validate first.
		if(!checkIPPrinceple($("#tIP"), /^(\d{1,3}\.){3}\d{1,3}$/, false, "IP不符合规则") || 
				!checkIPPrinceple($("#vdiIP"), null, false, "") || 
				!checkIPPrinceple($("#sDate"), null, false, "") ||
				!checkIPPrinceple($("#eDate"), null, false, "") || 
				!checkIPPrinceple($("#tPort"), /^\d{1,5}$/, true, "端口需小于5位数字") ||
				!checkIPPrinceple($("#Proto"), /^\w*$/, true, "类型不能有特殊字符"))
		{
			return;
		}
		
		// validate Date logic.
		if($("#sDate").val() && $("#eDate").val()) {
			if(Date.parse($("#eDate").val()) <= Date.parse($("#sDate").val())) {
				openAlert("结束日期不能小于或者等于开始日期.");
				
				return;
			}
		}
		
		// composite the data from page.
		var direction = $("input[type='radio']:checked").val();
		// ??????????????????????????????
		var vdiIp = $("#vdiIP").val().trim();
		var targetIp = $("#tIP").val().trim();
		var startTime = $("#sDate").val().trim();
		var endTime = $("#eDate").val().trim();
		var protocol = $("#Proto").val().trim();
		var remark = $("#fireWallRemark").val().trim();
		var port = $("#tPort").val().trim();
		
		// 如果是editOne情况， 则不牵扯重绘树和grid问题.
		if(fireWallObj.editOne) {
			fireWallObj.editOne.targetIp = targetIp;
			fireWallObj.editOne.startTime = startTime;
			fireWallObj.editOne.endTime = endTime;
			fireWallObj.editOne.protocol = protocol;
			fireWallObj.editOne.remark = remark;
			fireWallObj.editOne.port = port;
			fireWallObj.editOne.direction = direction;
			
			$.ajax({
				url: "updateFireWallOne.do",
				type: 'POST',
				dataType:"json",
				contentType: "application/json",
				data : JSON.stringify(fireWallObj.editOne)
			}).done(function(data) {
				console.debug("uupdate", data);
				
				if(data.result) {
					openAlert("修改成功", function() {
						jumpListPage();
					});
				}
				else {
					console.error("error occured when modify One");
					
					openAlert("修改失败");
				}
			});
			
			return;
		}
		
		// 如果是修改，则改变当前元素而不增加新元素.
		if(modify_obj_temp) {
			modify_obj_temp.vdiIp = vdiIp;
			modify_obj_temp.targetIp = targetIp;
			modify_obj_temp.startTime = startTime;
			modify_obj_temp.endTime = endTime;
			modify_obj_temp.protocol = protocol;
			modify_obj_temp.remark = remark;
			modify_obj_temp.port = port;
			modify_obj_temp.direction = direction;
		}
		else {
			var fwm_add_temp = new FireWallModel(vdiIp, targetIp, direction, 
					startTime, endTime, port, protocol, remark);
			
			if(fireWallObj.op == "edit") {
				fwm_add_temp.vdiInfoList = [new VDIIPBean($("#vdiIP").attr("vdiID"), $("#vdiIP").attr("vdiIP"))];
			}
			else {
				fwm_add_temp.vdiInfoList = vdi_insert_arr;
			}
			fireWallArray.push(fwm_add_temp);
		}
		
		redrawFireWallGrid();
		
		// clear vdi_insert_arr.
		vdi_insert_arr = [];
		// reset the tree display. 
		$.fn.zTree.getZTreeObj("vdiIPTree_ul").checkAllNodes(false);
		modify_obj_temp = null;
		
		// reset other conditions.
		$(".addFireWallAction").text("增加");
		$(".fireWallData tr").removeClass("list_choosedRow");
	});
	
	// del action.
	$(".fireWallData").delegate(".deleteFireWallBtn", "click", function(e) {
		openConfirm("确定要删除 targetIP = " + 
				$(this).parent().parent().find(".tTip").text() + "的防火墙吗？", 
				this, function() {
			console.debug($(this).parent().parent());
			var rowFireWall_temp = getRowDataFromGrid($(this).parent().parent());
			for(var obj_temp in fireWallArray) {
				if(fireWallArray[obj_temp].equals(rowFireWall_temp))
				{
					fireWallArray.splice(obj_temp, 1);
					
					break;
				}
			}
			
			redrawFireWallGrid();
		});
	}).delegate(".modifyRow", "click", function(e) {
		if($(e.target).hasClass("deleteFireWallBtn")) {
			e.stopPropagation();
			
			return;
		}
		
		// inite the condition.
		$(".addFireWallAction").text("修改");
		$(".validate-tooltip").css("display", "none");
		$("input").removeClass("validate-input-error");
		$(".fireWallData tr").removeClass("list_choosedRow");
		$(this).addClass("list_choosedRow");
		
		var rowFireWall_temp = getRowDataFromGrid(this);
		
		for(var obj_temp in fireWallArray) {
			if(fireWallArray[obj_temp].equals(rowFireWall_temp))
			{
				modify_obj_temp = fireWallArray[obj_temp];
				vdi_insert_arr = modify_obj_temp.vdiInfoList;
				
				break;
			}
		}
		
		// fill value in all input item with modify obj.
		$("#vdiIP").val(modify_obj_temp.vdiIp);
		$("#tIP").val(modify_obj_temp.targetIp);
		$("#sDate").val(modify_obj_temp.startTime);
		$("#eDate").val(modify_obj_temp.endTime);
		$("#tPort").val(modify_obj_temp.port);
		$("#Proto").val(modify_obj_temp.protocol);
		$("#fireWallRemark").val(modify_obj_temp.remark);
		modify_obj_temp.direction == 0 ? $($("input[type='radio']")[0]).attr("checked", true) : 
			$($("input[type='radio']")[1]).attr("checked", true);
		
		// fill the tree select.
		if(fireWallObj.op != "edit") {
			var treeObj_temp = $.fn.zTree.getZTreeObj("vdiIPTree_ul");
			var checkedNodes = treeObj_temp.getNodesByFilter(function(node) {
				if(node.isParent) {
					return false;
				}
				
				for(var node_temp in vdi_insert_arr) {
					if(vdi_insert_arr[node_temp].id == node.id) {
						return true;
					}
				}
				
				return false;
			});
			
			for(var i = 0; i < checkedNodes.length; i++) {
				treeObj_temp.checkNode(checkedNodes[i], true, true);
			}
		}
	});
	
	$(".action_VDIInfoSubmit").off("click").on("click", function() {
		// validate first.
		if(fireWallArray.length <= 0 && !fireWallObj.backUpEditFireWallIDList) {
			openAlert("请给表格中增加防火墙信息.");
			
			return;
		}
		
		if(fireWallObj.op == "edit") {
			submitModifyData();
		}
		else {
			submitData();
		}
	});
	
	function submitModifyData() {
		// composite data.
		var submitData_temp = {};
		
		submitData_temp.fireWallList = fireWallArray;
		submitData_temp.backUpEditFireWallIDList = 
			fireWallObj.backUpEditFireWallIDList.join();
		$.ajax({
		   url : "batchUpdateFireWallList.do?backUpEditFireWallIDList=" + submitData_temp.backUpEditFireWallIDList,
		   dataType : "json",
		   data : JSON.stringify(submitData_temp.fireWallList),//
		   type : "post",
		   contentType: "application/json"
		}).done(function(data) {
			console.debug("modify edit " , data);
			
			if(data.result) {
				 openAlert("修改成功.", function() {
					 fireWallObj.backUpEditFireWallIDList = null;

					 $("body").append(
							 "<form id='editFireWallTabForm' action= '" + BASE_PATH + 
							 "/firewallManagement/toFirewallTab_sitemesh_popup.do'>" +
							 "<input type='hidden' name='vdiId' value='" + 
							 $("#vdiIP").attr("vdiId") + "'></input></form>");
					 $("#editFireWallTabForm").submit();
				 });
			}
			else {
			     console.debug("error");
			   
			     openAlert("修改失败.");
			}
		});
	}
	
	// submit ajax method.
	function submitData() {
		// composite data.
		var submitData_temp = {};
		
		submitData_temp.fireWallList = fireWallArray;
		
		$.ajax({
		   url : "addFireWallList.do",
		   dataType : "json",
		   data : JSON.stringify(submitData_temp.fireWallList),//
		   type : "post",
		   contentType: "application/json"
		}).done(function(data) {
			console.debug("data", data);
			if(data.result) {
				openAlert("插入成功.", function() {
					console.debug("rrrreew", fireWallArray);
					
					$("body").append("<form class='fireWall_add_submit_form' action='firewallList.do' method='post'></form>");
					$(".fireWall_add_submit_form").submit();
				});
			}
			else {
				openAlert("插入失败");
			}
		});
		
		param = fireWallArray;
		window.open(BASE_PATH+"/firewallManagement/firewallApply.do","申请防火墙禀议模板",'scrollbars=yes,width=1000,height=600');
	}
	
	// validate IP principle.
	function checkIPPrinceple(e, regex, nullable, errMsg) {
		hideErrorMessage(e);
		if($(e).val().trim() == '') {
			if(!nullable) {
				showErrorMessage(e);
				return false;
			}
			
			return true;
		}
		
		if(regex && !regex.test($(e).val().trim())) {
			showErrorMessage(e, errMsg);
			
			return false;
		}
		
		return true;
	}
	
	// private method. show error.
	function showErrorMessage(target, msg) {
		$(target).addClass("validate-input-error");
		$(target).parent().find(".validate-tooltip").css("display", "block").text(msg || ERROR_MSG_NULL);
	}
	
	// hide error message.
	function hideErrorMessage(target) {
		$(target).removeClass("validate-input-error");
		$(target).parent().find(".validate-tooltip").css("display", "none");
	}
	
	// redraw the fireWall table.
	function redrawFireWallGrid() {
		var tbHtml = "";
		for(var tb in fireWallArray) {
			tbHtml += "<tr class='modifyRow' fid='" + fireWallArray[tb].id + "' ><td class='tOip' title='" + fireWallArray[tb].vdiIp + "'>" + fireWallArray[tb].vdiIp + "</td>" +
			"<td class='tTip' title='" + fireWallArray[tb].targetIp + "'>" + fireWallArray[tb].targetIp + "</td>" +
			"<td class='tDirection' title='" + (fireWallArray[tb].direction == 0 ? 'from' : 'to') + "'>" + (fireWallArray[tb].direction == 0 ? 'from' : 'to') + "</td>" +
			"<td class='tDate' title='" + (fireWallArray[tb].startTime ? fireWallArray[tb].startTime : "N/A") + " ~ " + (fireWallArray[tb].endTime ? fireWallArray[tb].endTime : "N/A") + "'>" + 
			(fireWallArray[tb].startTime ? fireWallArray[tb].startTime : "N/A") + " ~ " + (fireWallArray[tb].endTime ? fireWallArray[tb].endTime : "N/A") + "</td>" +
			"<td class='tPrototype' title='" + fireWallArray[tb].protocol + "'>" + (fireWallArray[tb].protocol ? fireWallArray[tb].protocol : "N/A") + "</td>" + 
			"<td class='tPort' title='" + fireWallArray[tb].port + "'>" + (fireWallArray[tb].port ? fireWallArray[tb].port : "N/A") + "</td>" +
			"<td class='tRemark' title='" + fireWallArray[tb].remark + "'>" + (fireWallArray[tb].remark ? fireWallArray[tb].remark : "N/A") + "</td>" +
			"<td style='width:99px'><div class='toolButton deleteFireWallBtn' style='min-width:25px;font-size:12px;'>删除</div></td>" +
			"<td style='width: 0px;'></td></tr>";
		}
		
		$("tbody.fireWallData").html(tbHtml);
		$("tbody.fireWallData td").css("padding-right", "0px");
		
		resetInputData();
	}
	
	// reset the input item.
	function resetInputData() {
		$($("input[type='radio']")[0]).attr("checked", true);
		
		if(fireWallObj.op != "edit") {
			$("#vdiIP").val("");
		}
		
		$("#tIP").val("");
		$("#sDate").val("");
		$("#eDate").val("");
		$("#tPort").val("");
		$("#Proto").val("");
		$("#fireWallRemark").val("");
	}
	
	// get firewall table row data, for compare...
	function getRowDataFromGrid(rowObj) {
		var vdiIP_del = $(rowObj).find(".tOip").text();
		var tarIP_del = $(rowObj).find(".tTip").text();
		var direction_del = $(rowObj).find(".tDirection").text();
		var duringTime_del = $(rowObj).find(".tDate").text().split("~");
		var proto_del = $(rowObj).find(".tPrototype").text() == "N/A" ? "" : $(rowObj).find(".tPrototype").text();
		var port_del = $(rowObj).find(".tPort").text() == "N/A" ? "" : $(rowObj).find(".tPort").text();
		var remark_del = $(rowObj).find(".tRemark").text() == "N/A" ? "" : $(rowObj).find(".tRemark").text();
		var vid = $(rowObj).attr("fid") == "undefined" ? undefined : $(rowObj).attr("fid");

		return new FireWallModel(vdiIP_del, tarIP_del, direction_del == "from" ? 0 : 1, 
				duringTime_del[0].trim(), duringTime_del[1].trim(), port_del, proto_del, 
				remark_del, vid);
	}
	
	// fill data when edit firewall.
	function fillFireWallBaseData(dataBean) {
		$("#vdiIP").val(dataBean.vdiIP);
		$("#tIP").val(dataBean.targetIp);
		$("#sDate").val(dataBean.startTime);
		$("#eDate").val(dataBean.endTime);
		$("#tPort").val(dataBean.port);
		$("#Proto").val(dataBean.protocol);
		$("#fireWallRemark").val(dataBean.remark);
		dataBean.direction == 0 ? $($("input[type='radio']")[0]).attr("checked", true) :
			$($("input[type='radio']")[1]).attr("checked", true)
	}
	
	// class FireWallModel.
	function FireWallModel(vdiIp, targetIp, direction, startTime, endTime, port, protocol, remark, id) {
		this.vdiIp = vdiIp;
		this.targetIp = targetIp;
		this.direction = direction;
		this.startTime = startTime;
		this.endTime = endTime;
		this.port = port;
		this.protocol = protocol;
		this.remark = remark;
		this.id = id;
	}
	
	// vdi ip info.
	function VDIIPBean(id, ip) {
		this.id = id;
		// process ip.
		this.ip = ip.split("-")[1] == undefined ? ip : ip.split("-")[1];
	}
	
	// 当取消当前操作， 返回List页面.
	$("#cancelButton").on("click",function(){
		jumpListPage();
	});
	
	// 跳转到List页面.
	function jumpListPage(){
		$("#jumpListPageForm").submit();
	}
});